import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/index_nav_page/smart_home_index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'dart:typed_data';

import '../../app_main.dart';

/// 门店信息
class SmartHome3DUploadPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHome3DUploadPage";

  final String shid;
  final String webUrl;
  final List<ColumnListBean> columnList;
  final ColumnListBean currentColumn;

  const SmartHome3DUploadPage(
      {Key key, this.shid, this.webUrl, this.columnList, this.currentColumn,}) : super(key:key);

  @override
  _SmartHome3DUploadPageState createState() => _SmartHome3DUploadPageState();

  static Future<String> navigatorPush(BuildContext context, String shid, String webUrl, List<ColumnListBean> columnList, ColumnListBean currentColumn,){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHome3DUploadPage(
          shid: shid,
          webUrl: webUrl,
          columnList: columnList,
          currentColumn: currentColumn,
        ),
        routeName: SmartHome3DUploadPage.ROUTER
    );
  }
}

class _SmartHome3DUploadPageState
    extends BaseState<SmartHome3DUploadPage> {


  TextEditingController _linkController;

  ///网址
  String _webUrl = "";
  InAppWebViewController  _webViewController;

  @override
  void initState() {
    super.initState();
    _webUrl = widget?.webUrl??"";
    _linkController = TextEditingController();
    if(StringUtils.isEmpty(_webUrl)){
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        loadPasteUrl();
      });
    }
  }


  @override
  void dispose() {
    _linkController?.clear();
    _linkController?.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      loadPasteUrl();
    }
  }


  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        if(StringUtils.isEmpty(_webUrl))_toLinkWidget(),
        if(StringUtils.isEmpty(_webUrl))_toNoLinkHintWidget(),
        if(StringUtils.isNotEmpty(_webUrl))_toWebViewWidget(),
        if(StringUtils.isNotEmpty(_webUrl))_toBottomWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "3D全景效果图",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }




  ///标题
  Widget _toLinkWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Expanded(
            child: VgTextField(
              controller: _linkController,
              keyboardType: TextInputType.text,
              autofocus: true,
              textAlign: TextAlign.left,
              style: TextStyle(
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontSize: 14),
              decoration: new InputDecoration(
                  counterText: "",
                  hintText: "链接地址",
                  border: InputBorder.none,
                  hintStyle: TextStyle(
                      fontSize: 14,
                      color: Color(0XFFB0B3BF))),
              maxLines: 1,
              zhCountEqEnCount: true,
              onChanged: (value){
                // _notifyChange();
              },
            ),
          ),
          Spacer(),
          _toPasteWidget(),
        ],
      ),
    );
  }

  ///粘贴布局
  _toPasteWidget(){
    return Container(
      height: 24,
      width: 47,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
        color: Color(0XFFF0F2F5),
      ),
      child: Text(
        "粘贴",
        style: TextStyle(
            fontSize: 12,
            color: ThemeRepository.getInstance().getCardBgColor_21263C()
        ),
      ),
    );
  }

  ///剪切板中无链接
  _toNoLinkHintWidget(){
    return Container(
      height: 34,
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: 15),
      child: Row(
        children: [
          Image.asset(
            "images/icon_no_link_hint.png",
            width: 14,
          ),
          SizedBox(width: 4,),
          Text(
            "剪切板中未检测到有效链接",
            style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getCardBgColor_21263C()
            ),
          ),
        ],
      ),
    );
  }

  ///webview
  _toWebViewWidget(){
    return Expanded(
      child: Container(
        color: Color(0xFFF6F7F9),
        child: InAppWebView(
          initialUrl: _webUrl,
          onWebViewCreated:
              (InAppWebViewController  webController) {
            _webViewController = webController;
          },
          onLoadStop: (InAppWebViewController controller, String url) async{
            _webViewController
                .evaluateJavascript(source:_getJS())
                .then((result) {
              setState(() {
                String title = result;
                if (!StringUtils.isEmpty(title)) {
                  if (title.startsWith("\"")) {
                    title = title.substring(1);
                  }
                  if (title.endsWith("\"")) {
                    title =
                        title.substring(0, title.length - 1);
                  }
                  if (title.length > 8) {
                    title =
                        title.substring(0, 8);
                  }
                }
              });
            });
          },
        ),
      ),
    );
  }

  ///底部操作
  _toBottomWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        // loading(true, msg: "正在截屏");
        // String imagePath = await _captureWidget();
        // loading(false);
        String clipPath = await MatisseUtil.clipOneImage(context, scaleX: 3, scaleY: 4,
            onRequestPermission: (msg)async{
              bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: msg,
                cancelText: "取消",
                confirmText: "去授权",
                confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                cancelBgColor: Color(0xFFF6F7F9),
                titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                widgetBgColor: Colors.white,
              );
              if (result ?? false) {
                PermissionUtil.openAppSettings();
              }
            });
        if(clipPath == null){
          return;
        }
        if(StringUtils.isNotEmpty(clipPath)){
          if(StateHelper.has<SmartHomePublishPage>()){
            RouterUtils.pop(context, result: clipPath);
          }else{
            String router = SmartHomeStoreDetailsPage.ROUTER;
            if(!StateHelper.has<SmartHomeIndexNavPage>() && !StateHelper.has<IndexNavPage>()){
              router = AppMain.ROUTER;
            }
            SmartHomePublishPage.navigatorPush(context,
                widget?.shid, "03", widget?.columnList, widget?.currentColumn,
                linkUrl: _webUrl,
                coverPath: clipPath,
              router: router
            );
          }

        }
      },
      child: Container(
        height: 56,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        child: Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
          ),
          alignment: Alignment.center,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "下一步，设置封面",
                style: TextStyle(
                    fontSize: 15,
                    color: Colors.white
                ),
              ),
              SizedBox(width: 6,),
              Image.asset(
                "images/icon_arrow_white.png",
                width: 6,
              ),
            ],
          ),
        ),
      ),
    );
  }


  Future<void> loadPasteUrl() async {
    ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data != null) {
      if (StringUtils.isNotEmpty(data.text)) {
        var newWebUrl = getURLFromShearPlate(data.text);
        if (newWebUrl == _webUrl) {
          return;
        }
        if (StringUtils.isNotEmpty(newWebUrl)){
          if (_webViewController != null){
            _webViewController.loadUrl(url: newWebUrl);
          }
          setState(() {
            _webUrl = newWebUrl;
          });
        }
      }
    }
  }

  /// 获取剪切板中的网址
  String getURLFromShearPlate(String shearStr){
    String result = "";
    var reg = r"((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+";
    var vs = RegExp(reg).stringMatch(shearStr);
    if (StringUtils.isNotEmpty(vs)){
      result = vs;
    }
    return result;
  }

  ///   注入js获取title
  String _getJS(){
    if (_webUrl != null && _webUrl.contains("mp.weixin.qq.com")){
      return "window.msg_title";
    }else{
      return "document.title";
    }
  }
  /// 通过 RenderRepaintBoundary 生成图片
  Future<String> _captureWidget() async{
    Uint8List picBytes = await _webViewController.takeScreenshot();
    String imagePath = await FileUtils.createFileFromUnit8ListInDirectory((await getExternalStorageDirectory()).path + "/widget to img/", picBytes);
    return imagePath;
  }


}
